//
//  LogInController.m
//  operativeSide-2.0
//
//  Created by 王春程 on 2016/12/14.
//  Copyright © 2016年 王春程. All rights reserved.
//

#import "LogInController.h"
#import "LogInManager.h"
#import "ChangePSDController.h"

@interface LogInController ()<UITextFieldDelegate>
@property (strong, nonatomic)        LogInManager *manager;
@property (assign, nonatomic)        BOOL isRember;
@property (assign, nonatomic)        BOOL isUsername;

@property (weak, nonatomic) IBOutlet UITextField *userNameField;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;

@property (weak, nonatomic) IBOutlet UIButton *remeberBtn;
@property (weak, nonatomic) IBOutlet UIButton *forgetBtn;

@property (weak, nonatomic) IBOutlet UIButton *logInBtn;
@property (weak, nonatomic) IBOutlet UIView *backView;

@property (weak, nonatomic) IBOutlet UIImageView *backImageView;

@end

@implementation LogInController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self registerForKeyboardNotifications];
    self.manager = [LogInManager sharedManager];
    self.userNameField.attributedPlaceholder = [[NSMutableAttributedString alloc]initWithString:@"请输入账号" attributes:@{NSForegroundColorAttributeName:RGB(204, 204, 204)}];
    self.passwordField.attributedPlaceholder = [[NSMutableAttributedString alloc]initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName:RGB(204, 204, 204)}];
    
    
    
    [self getCode];
}


- (void)getCode {
    
    WS(weakSelf);
    self.logInBtn.enabled = NO;
    self.backImageView.userInteractionEnabled = YES;
    self.backView.userInteractionEnabled = YES;
    _userNameField.delegate = self;
    _passwordField.delegate = self;
    
    
    RACSignal *passWordSignal =
    [self.passwordField.rac_textSignal map:^id _Nullable(NSString * _Nullable value) {
        
        return @(value.length > 5 && value.length < 16);
    }];
    
    //创建按钮信号
    RACSignal *btnSignal =
    [RACSignal combineLatest:@[passWordSignal] reduce:^id _Nullable(NSNumber *passwordIsVal){
        return @([passwordIsVal boolValue] && weakSelf.userNameField.text && weakSelf.userNameField.text.length != 0);
    }];
    
    RAC(self.logInBtn,enabled) =
    [btnSignal map:^id _Nullable(NSNumber *value) {
        return @([value boolValue]);
    }];
    
    
    [[self.logInBtn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [[weakSelf logInSignal] subscribeNext:^(NSNumber *x) {
            weakSelf.logInBtn.enabled = [x boolValue];

            if([x boolValue]) {
                NSLog(@"登录成功");
                [self.navigationController pushViewController:[[ChangePSDController alloc] init] animated:YES];
            } else {

                NSLog(@"登录失败");
            }
        }];
    }];
    

    [[self.remeberBtn rac_signalForControlEvents:UIControlEventTouchUpInside]
     subscribeNext:^(__kindof UIControl * _Nullable x) {
        static BOOL flag;
        flag = !flag;
        self.remeberBtn.selected = flag;
        self.isRember = flag;
    }];
    
    
    [[self.forgetBtn rac_signalForControlEvents:UIControlEventTouchUpInside]
     subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSLog(@"忘记密码");
    }];
}

- (RACSignal *)logInSignal
{
    @weakify(self)
   return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
       @strongify(self)
       
       [self.manager logInWithUserName:self.userNameField.text
                          withPassWord:self.passwordField.text
                          withIsRember:self.isRember
                              compelet:^(BOOL flag) {
                                  [subscriber sendNext:@(flag)];
                                  [subscriber sendCompleted];
           
       }];
       return nil;

   }];
}

- (void)registerForKeyboardNotifications

{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShown:)
     
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

//实现当键盘出现的时候计算键盘的高度大小。用于输入框显示位置
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    CGFloat duration = [aNotification.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
    CGRect frame = [aNotification.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    WS(ws);
    if (self.isUsername == YES) {
        CGRect rect = ws.view.bounds;
        rect.origin.y = 286 + 35 - frame.origin.y;
        if (rect.origin.y > 0) {
            [UIView animateWithDuration:duration animations:^{
                NSLog(@"%f",rect.origin.y);
                ws.view.bounds = rect;
            }];
        }
        
    }else {
        
        CGRect rect = ws.view.bounds;
        rect.origin.y = 286 + 70 - frame.origin.y;
        if (rect.origin.y > 0) {
            [UIView animateWithDuration:duration animations:^{
                ws.view.bounds = rect;
            }];
        }
    }
}

//当键盘隐藏的时候
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    WS(ws);
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = ws.view.bounds;
        rect.origin.y = 0;
        ws.view.bounds = rect;
    }];
}


#pragma mark -_- TextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    if(textField == self.userNameField) {
        self.isUsername = YES;
    } else {
        self.isUsername = NO;
    }
    
    return YES;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

    [self.userNameField resignFirstResponder];
    [self.passwordField resignFirstResponder];

}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardDidShowNotification
                                                  object:nil];
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
